<template>
  <div class="employees-detail-container">
    <div class="app-container">
      <el-card>
        <!-- 放置表单 -->
        <el-form
          ref="userForm"
          label-width="120px"
          style="margin-left: 120px; margin-top: 30px"
          :model="userInfo"
          :rules="rules"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="userInfo.username" style="width: 300px" />
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="userInfo.mobile" style="width: 300px" disabled />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker v-model="userInfo.timeOfEntry" type="date" class="inputW" />
          </el-form-item>
          <el-form-item label="员工头像">
            <ImageUpload ref="refUpload" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updateUserInfo">更新</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { employeeInfoApi } from '@/api/user'
import { saveEmployeeInfoApi } from '@/api/employees'
export default {
  name: 'EmployeesDetail',
  data() {
    return {
      userInfo: {
        timeOfEntry: '', // 入职时间
        username: '', // 姓名
        mobile: '', // 手机
        staffPhoto: '' // 头像
      },
      rules: {
        username: [{ required: true, message: '用户名不可为空', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '入职时间不可为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    userID() {
      return this.$route.params.id
    }
  },
  created() {
    this.employeeInfo()
  },
  methods: {
    // 回填员工信息
    async employeeInfo() {
      const { data: res } = await employeeInfoApi(this.userID)
      this.userInfo = res.data
      // 获取组件中的fileList更改值
      this.$refs.refUpload.fileList = [{ url: res.data.staffPhoto }]
    },
    // 兜底校验
    updateUserInfo() {
      this.$refs.userForm.validate(valid => {
        if (!valid) return
        const refUpload = this.$refs.refUpload
        console.log(refUpload)
        if (!refUpload.isUpLoad) {
          this.$message.error('请等待图片上传完毕')
          return
        }
        // 调借口之前获取上传图片的地址
        const url = this.$refs.refUpload.fileList[0]?.url
        this.userInfo.staffPhoto = url || ''
        saveEmployeeInfoApi(this.userInfo)
          .then(res => {
            this.$message.success('更新 成功')
            this.$router.push('/employees/index')
          })
          .catch(err => {
            console.log(err)
            this.$message.error('更新失败')
          })
      })
    }
  }
}
</script>
